package com.school.admin.common.aop;

import com.google.common.collect.Maps;
import com.google.common.util.concurrent.RateLimiter;
import com.school.admin.common.annotation.Limiting;
import com.school.admin.common.handler.GlobalException;
import com.school.admin.common.handler.GlobalExceptionEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;

import static com.google.common.util.concurrent.RateLimiter.*;

/**
 * @program: backstage-admin
 * @description:
 * @author: sunpx
 * @create: 2022-04-20 15:27
 **/
@Slf4j
@Aspect
@Component
public class LimitingAop {


    private final Map<String, RateLimiter> limitMap = Maps.newConcurrentMap();

    @Around("@annotation( com.school.admin.common.annotation.Limiting)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取注解
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Limiting annotation = method.getAnnotation(Limiting.class);


        RateLimiter rateLimiter = null;
        //判断注解是否存在
        if (annotation != null) {
            //获取key
            String key = annotation.key();
            if (!limitMap.containsKey(key)) {
                rateLimiter = create(annotation.permitsPerSecond());
                limitMap.put(key, rateLimiter);
            }
            rateLimiter = limitMap.get(key);
            boolean acquire = rateLimiter.tryAcquire(annotation.timeout(), annotation.timeunit());

            // 不存在抛出异常
            if (!acquire) {
                String msg = annotation.msg();
                if (StringUtils.isEmpty(msg)) {
                    msg = GlobalExceptionEnum.OPERATING_FREQUENCY_IS_TOO_HIGH.getMessage();
                }
                throw new GlobalException(GlobalExceptionEnum.OPERATING_FREQUENCY_IS_TOO_HIGH.getCode(), msg);
            }
        }
        return joinPoint.proceed();
    }

}
